<template>
	<view class="page-content">
		<view class="f-tabs">
			<view :class="active == 0?'active':''" @click="active=0">门店信息</view>
			<view :class="active == 1?'active':''" @click="active=1">聚合码</view>
			<view :class="active == 2?'active':''" @click="active=2">WIFI码</view>
		</view>

		<view class="my-forms" v-show="active==0">
			<uni-forms :modelValue="formData" :label-width="90">
				<uni-forms-item label="门店位置">
					<view class="input-border" @click="openCL">
						<view v-if="formData.store_tencent_latitude">
							{{formData.store_tencent_latitude}},{{formData.store_tencent_longitude}}
						</view>
						<view v-else>
							请选择
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="store_address">
					<uni-easyinput type="text" v-model="formData.store_address" placeholder="请输入详细地址" />
				</uni-forms-item>
				<uni-forms-item label="门店名称" name="store_name">
					<uni-easyinput type="text" v-model="formData.store_name" placeholder="请输入门店名称" />
				</uni-forms-item>
				<uni-forms-item label="抖音POI" name="business_douyin_poi_id">
					<view class="input-border" @click="goCheckPoi">
						<view v-if="formData.business_douyin_poi_id">
							{{formData.business_douyin_poi_id}}
						</view>
						<view v-else>
							请选择
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="推广视频" name="business_custom_video_link">
					<uni-easyinput type="text" v-model="formData.business_custom_video_link" placeholder="请输入推广视频链接" />
				</uni-forms-item>
				<uni-forms-item label="微信商户号" name="business_wechat_mchid">
					<!-- :disabled="isEidt" -->
					<uni-easyinput type="text" v-model="formData.business_wechat_mchid" placeholder="用于实时收款的官方账号" />
				</uni-forms-item>
				<uni-forms-item label="支付宝商户号" name="business_alipay_mchid">
					<uni-easyinput type="text" v-model="formData.business_alipay_mchid" placeholder="用于实时收款的官方账号" />
				</uni-forms-item>
				<uni-forms-item label="授权序列号" name="business_alipay_auth_token">
					<uni-easyinput type="text" v-model="formData.business_alipay_auth_token" placeholder="用于授权收款" />
				</uni-forms-item>
				<!-- 	<uni-forms-item label="微信商户密钥" name="business_wechat_mchkey">
					:disabled="isEidt"
					<uni-easyinput type="text" v-model="formData.business_wechat_mchkey" placeholder="用于授权收款" />
				</uni-forms-item> -->

				<uni-forms-item label="上传门头照">
					<uni-file-picker limit="1" style="color:grey" :del-icon="false" disable-preview
						:imageStyles="imageStyles" file-mediatype="image" @select="selectPic">
						<image v-if="formData.store_head_image" style="width: 52px;height: 52px;"
							:src="picServiceUrl+formData.store_head_image" mode="">
						</image>
						<view v-else>
							选择
						</view>
					</uni-file-picker>
				</uni-forms-item>

				<uni-forms-item label="行业" name="subject_type">
					<uni-data-picker v-model="formData.subject_type" v-slot:default="{data, error, options}"
						:clear-icon="false" :localdata="hangyeRange" popup-title="请选择">
						<view v-if="error" class="error input-border">
							<text>{{error}}</text>
						</view>
						<view v-else-if="data.length" class="selected input-border">
							<text>{{data[0].text}} - {{data[1].text}}</text>
						</view>
						<view v-else class="input-border">
							<text>请选择</text>
						</view>
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="营业时间">
					<view class="pick-time">
						<picker mode="time" class="picker" :value="startTime" @change="bindChange"
							data-name="startTime">
							<view>{{startTime?startTime:"请选择"}}</view>
						</picker>
						<view class="fenge">
							至
						</view>
						<picker mode="time" class="picker" :value="endTime" @change="bindChange" data-name="endTime">
							<view>{{endTime?endTime:"请选择"}}</view>
						</picker>
					</view>
				</uni-forms-item>

				<uni-forms-item label="平台优惠">
					<!-- :readonly="isEidt" -->
					<uni-data-picker v-model="formData.member_discount" :localdata="huiyuanRange" popup-title="请选择折扣">
						<view class="member-discount" v-if="formData.member_discount==100">
							无折扣
						</view>
						<view class="member-discount" v-else-if="formData.member_discount">
							{{formData.member_discount/10+"折"}}
						</view>
						<view class="member-discount" v-else>
							请选择
						</view>
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="WIFI名称">
					<uni-easyinput type="text" suffixIcon="location-filled" @iconClick="iconWifi"
						v-model="formData.store_wifi_name" placeholder="店内WIFI名称" />
				</uni-forms-item>
				<uni-forms-item label="WIFI密码">
					<uni-easyinput type="text" v-model="formData.store_wifi_password" placeholder="店内WIFI密码" />
				</uni-forms-item>
			</uni-forms>

			<label class="agreement" @click="clickAgreement">
				<radio class="my-radio" :checked="isAgreement" />同意
				<text @click.stop="goAgreement">《在花一商户服务协议》</text>
			</label>
			<button type="primary" @click="submitForm">提交</button>
		</view>


		<view class="item-bg" v-show="active==1">
			<view class="item_border">
				<image :src="codeImg" @click="canstopic(codeImg)" v-show="codeImg" mode="widthFix" style="width: 100%;">
				</image>
				<view class="tip" v-show="!codeImg">
					正在绘制...
				</view>
			</view>

			<button class="eidt-button" type="primary" @click="saveShareImg(codeImg)">保存到相册</button>
		</view>

		<view class="item-bg" v-show="active==2">
			<view class="item_border">
				<image :src="wifiImg" @click="canstopic(wifiImg)" v-show="wifiImg" mode="widthFix" style="width: 100%;">
				</image>
				<view class="tip" v-show="!wifiImg">
					正在绘制...
				</view>
			</view>

			<button class="eidt-button" type="primary" @click="saveShareImg(wifiImg)">保存到相册</button>
		</view>

		<view class="canvas-position">
			<canvas id="qrcode_wifi" canvas-id="qrcode_wifi"
				:style="{'width': `${size}px`, 'height': `${size+80}px`}" />
		</view>

		<view class="canvas-position">
			<canvas id="qrcode" canvas-id="qrcode" :style="{'width': `${size}px`, 'height': `${qrHight}px`}" />
		</view>
	</view>
</template>

<script>
	import OptionJson from "../../../utils/optionJson.js"
	import uQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js'
	const app = getApp();
	export default {
		data() {
			return {
				formData: {
					offline_business_id: "",
					store_name: "", //		门店名称
					business_douyin_poi_id: "", //		门店名称
					business_custom_video_link: "", //		视频链接
					store_address: "", //		门店详细地址
					store_tencent_longitude: "", //	门店经度(腾讯)
					store_tencent_latitude: "", //	门店纬度(腾讯)
					store_head_image: "", //		门店头照片(主图 支付可展示)  此参数调用上传门店头照片的路径填写
					business_wechat_mchid: "", //		商家微信商户号
					business_alipay_mchid: "", //		商家支付宝商户号
					business_alipay_auth_token: "", //		商家授权序列号
					subject_type: [], //			主体类型 个体户、企业、党政、机关及事业单位、其他组织
					member_discount: "", //			会员优惠(0.01~0.99之间 1为整)
					business_wechat_mchkey: "",
					store_hours_start: "",
					store_hours_end: "",
					store_wifi_name: "",
					store_wifi_password: "",
					promoter_id: "", //推广人ID 
					distribution_rate: "", //分销百分比
				},
				huiyuanRange: [],
				hangyeRange: [],
				startTime: "",
				endTime: "",
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						radius: '5px'
					}
				},
				active: 0, //0 基础信息 1二维码
				isEidt: false, //修改
				userInfo: null,
				maxNum: '',
				size: 600,
				qrHight: 900,
				margin: 10,
				backgroundColor: '#FFFFFF',
				foregroundColor: '#000000',
				isAgreement: false,
				picServiceUrl: app.globalData.picServiceUrl,
				bgPath: null,
				codeImg: null,
				wifiImg: null
			}
		},
		onLoad(e) {
			if (e && e.id) {
				this.formData.offline_business_id = e.id
				this.formData.promoter_id = e.sharid
				this.formData.distribution_rate = e.rate
			}
			this.hangyeRange = OptionJson.jylmJson;

			let hr = [];
			for (let i = 1; i <= 95; i++) {
				hr.push({
					"value": i,
					"text": i / 10 + '折',
				})
			}
			this.huiyuanRange = hr;

			//#ifdef  MP-ALIPAY
			uni.showModal({
				content: '请用微信扫码填写',
				showCancel: false,
				confirmText: '好的',
				confirmColor: '#333',
				success: function(res) {
					uni.navigateBack({
						delta: 1
					})
				},
				fail: function(res) {}
			})
			// #endif

			this.getInfo();
		},
		onShow() {
			let poi_id = uni.getStorageSync("pcikPOI")
			console.log(poi_id)
			if (poi_id) {
				this.formData.business_douyin_poi_id = poi_id
				uni.setStorageSync("pcikPOI", '')
			}

		},
		methods: {
			goCheckPoi() {
				uni.navigateTo({
					url: "/pages/newMy/generateCode/checkPoi?name=" + this.formData.store_name
				})
			},
			iconWifi() {
				//#ifdef  MP-WEIXIN
				wx.startWifi({
					success: () => {
						wx.getConnectedWifi({
							success: (res) => {
								console.log(res)
								if (res.errCode == 0) {
									return this.formData.store_wifi_name = res.wifi.SSID;
								}
							}
						})
					}
				})
				// #endif

				//#ifdef  MP-ALIPAY
				my.startWifi({
					success: () => {
						my.getConnectedWifi({
							success: (res) => {
								console.log(res)
								if (res.errCode == 0) {
									return this.formData.store_wifi_name = res.wifi.SSID;
								}
							}
						})
					}
				})
				// #endif

			},
			goAgreement() {
				uni.navigateTo({
					url: "../../agreement/index?name=在花一商户服务协议.txt"
				})
			},
			clickAgreement() {
				this.isAgreement = !this.isAgreement;
			},
			//点击保存到相册
			saveShareImg(url) {
				var that = this;
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success(res) {
						uni.showModal({
							content: '图片已保存到相册，赶紧晒一下吧~',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#333',
							success: function(res) {
								if (res.confirm) {}
							},
							fail: function(res) {}
						})
					},
					fail: function(res) {
						uni.showToast({
							title: res.errMsg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			generateWifi(str, _id) {
				let modules = uQRCode.getModules({
					text: str,
					errorCorrectLevel: uQRCode.errorCorrectLevel.H,
					// 'foreground.image': {
					// 	src: '/static/image/icon2/wifi.png',
					// 	width: 0.25,
					// 	height: 0.25,
					// 	align: ['center', 'center'],
					// 	anchor: [0, 0]
					// }
				})

				let size = this.size;
				let margin = 10;
				let xdev = 0;
				let ydev = 0;

				let tileSize = (size - 5 * 2) / modules.length
				// 获取绘图所需的上下文
				let ctx = uni.createCanvasContext('qrcode_wifi', this)

				ctx.setFillStyle(this.backgroundColor)
				ctx.fillRect(xdev, ydev, size, size)
				for (var row = 0; row < modules.length; row++) {
					for (var col = 0; col < modules.length; col++) {
						// 计算每一个小块的位置
						var x = col * tileSize + margin + xdev
						var y = row * tileSize + margin + ydev
						var w = tileSize
						var h = tileSize

						var style = modules[row][col] ? this.foregroundColor : this.backgroundColor
						ctx.setFillStyle(style)
						ctx.fillRect(x, y, w, h)
					}
				}

				ctx.setFontSize(30);
				ctx.setFillStyle("#000");
				ctx.setTextAlign("center");
				let text = "WIFI.9102" + _id;
				ctx.fillText(text, this.size / 2, (ydev + size) * 1.08, size);


				ctx.draw();
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: "qrcode_wifi",
						success: (res) => {
							this.wifiImg = res.tempFilePath;
						}
					})
				}, 500)

			},
			generateQrcode(str, _id) {
				let modules = uQRCode.getModules({
					text: str,
					errorCorrectLevel: uQRCode.errorCorrectLevel.H
				})

				let size = 270;
				let margin = 10;
				let xdev = 165;
				let ydev = 315;

				let tileSize = (size - 5 * 2) / modules.length
				// 获取绘图所需的上下文
				let ctx = uni.createCanvasContext('qrcode', this)
				// 开始绘制
				ctx.drawImage(
					this.bgPath,
					0,
					0,
					this.size,
					this.qrHight,
				);

				ctx.setFillStyle(this.backgroundColor)
				ctx.fillRect(xdev, ydev, size, size)
				for (var row = 0; row < modules.length; row++) {
					for (var col = 0; col < modules.length; col++) {
						// 计算每一个小块的位置
						var x = col * tileSize + margin + xdev
						var y = row * tileSize + margin + ydev
						var w = tileSize
						var h = tileSize

						var style = modules[row][col] ? this.foregroundColor : this.backgroundColor
						ctx.setFillStyle(style)
						ctx.fillRect(x, y, w, h)
					}
				}

				ctx.setFontSize(24);
				ctx.setFillStyle("#000");
				ctx.setTextAlign("center");
				let text = "NO.9102" + _id;
				ctx.fillText(text, this.size / 2, (ydev + size) * 1.08, size);


				ctx.draw();
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: "qrcode",
						success: (res) => {
							this.codeImg = res.tempFilePath;
						}
					})
				}, 500)

			},
			canstopic(url) {
				uni.previewImage({
					urls: [url] // 需要预览的图片http链接列表
				})
			},
			getInfo() {
				uni.request({
					url: app.globalData.serviceUrl + '/UserMiniProgramController/getUserInfo',
					data: {
						key: uni.getStorageSync('userKey')
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: res => {
						var data = res.data;
						if (data.state == 1) {
							if (data.data.isOfflineBusiness) {
								let bus = data.data.offlineBusiness;
								this.userInfo = bus;
								console.log(bus, 'busbusbsusbusbus')
								if (bus.id) {
									this.isEidt = true;
									this.formData = {
										offline_business_id: bus.id,
										store_name: bus.storeName,
										business_douyin_poi_id: bus.businessDouyinPoiId,
										business_custom_video_link: bus.businessCustomVideoLink,
										store_address: bus.storeAddress,
										store_tencent_longitude: bus.storeTencentLongitude,
										store_tencent_latitude: bus.storeTencentLatitude,
										store_head_image: bus.storeHeadImage,
										business_wechat_mchid: bus.businessWechatMchid,
										business_alipay_mchid: bus.businessAlipayMchid,
										business_alipay_auth_token: bus.businessAlipayAuthToken,
										subject_type: bus.subjectType,
										member_discount: bus.memberDiscount * 100,
										business_wechat_mchkey: bus.businessWechatMchkey,
										store_wifi_name: bus.storeWifiName,
										store_wifi_password: bus.storeWifiPassword,
									}
									this.startTime = bus.storeHoursStart;
									this.endTime = bus.storeHoursEnd;
									uni.downloadFile({
										url: "https://zaihuayi.top/picture/static/qrcode_bg.png",
										success: (res) => {
											this.bgPath = res.tempFilePath;
											this.generateQrcode(
												'https://zaihuayi.top/payh5/#/?id=' +
												this.userInfo.id, this.userInfo.id);

											this.generateWifi(
												'https://zaihuayi.top/generatewifi?id=' +
												this.userInfo.id, this.userInfo.id)
										}
									})

								} else {
									this.huiyuanRange.push({
										"value": 100,
										"text": '无折扣',
									})
								}
							}

						} else if (data.state == 2) {
							uni.navigateTo({
								url: '../../login/index'
							});

						} else {
							uni.showToast({
								title: data.notice,
								icon: "none"
							})
						}
					}
				});

			},
			submitForm() {
				let form = this.formData;
				form.key = uni.getStorageSync('userKey');
				form.store_hours_start = this.startTime;
				form.store_hours_end = this.endTime;

				if (!this.formData.store_tencent_latitude) {
					return uni.showToast({
						title: "请选择门店位置",
						icon: "none"
					})
				}
				if (!this.formData.store_address) {
					return uni.showToast({
						title: "请输入详细地址",
						icon: "none"
					})
				}
				if (!this.formData.store_name) {
					return uni.showToast({
						title: "请输入门店名称",
						icon: "none"
					})
				}
				// if (!this.formData.business_wechat_mchid) {
				// 	return uni.showToast({
				// 		title: "请输入微信商户号",
				// 		icon: "none"
				// 	})
				// }
				// if (!this.formData.business_wechat_mchkey) {
				// 	return uni.showToast({
				// 		title: "请输入微信秘钥",
				// 		icon: "none"
				// 	})
				// }
				// if (!this.formData.business_alipay_mchid) {
				// 	return uni.showToast({
				// 		title: "请输入支付宝商户号",
				// 		icon: "none"
				// 	})
				// }
				// if (!this.formData.business_alipay_auth_token) {
				// 	return uni.showToast({
				// 		title: "请输入授权序列号",
				// 		icon: "none"
				// 	})
				// }
				if (!this.formData.store_head_image) {
					return uni.showToast({
						title: "请选择门头照",
						icon: "none"
					})
				}
				if (!this.formData.subject_type.length) {
					return uni.showToast({
						title: "请选择行业",
						icon: "none"
					})
				}
				if (!this.formData.store_hours_start) {
					return uni.showToast({
						title: "请选择开始营业时间",
						icon: "none"
					})
				}
				if (!this.formData.store_hours_end) {
					return uni.showToast({
						title: "请选择结束营业时间",
						icon: "none"
					})
				}

				if (!this.formData.member_discount) {
					return uni.showToast({
						title: "请选择折扣",
						icon: "none"
					})
				}

				if (!this.isAgreement) {
					return uni.showToast({
						title: "请阅读并同意协议",
						icon: "none"
					})
				}

				uni.request({
					url: app.globalData.serviceUrl + '/UserMiniProgramController/updateOfflineBusinessBaseInfo',
					data: form,
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: res => {
						var data = res.data;
						if (data.state == 1) {
							uni.showToast({
								title: "提交成功",
								icon: "none"
							})
							setTimeout(() => {
								uni.setStorageSync("userRole", true)
								uni.navigateTo({
									url: "../newMy"
								})
							}, 2000)
						} else {
							uni.showToast({
								title: data.notice,
								icon: "none"
							})
						}
					}
				});
			},
			// 上传成功
			success(e) {
				console.log('上传成功', e)
			},
			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			selectPic(res) {
				console.log(res.tempFilePaths[0])
				uni.compressImage({
					src: res.tempFilePaths[0], // 图片路径
					quality: 40, // 压缩质量
					success: (resCompress) => {
						console.log(resCompress)
						uni.uploadFile({
							url: app.globalData.serviceUrl +
								'/UserMiniProgramController/doUploadOfflineBusinessStoreHeadImage', //仅为示例，非真实的接口地址
							filePath: resCompress,
							name: 'file',
							success: (uploadFileRes) => {
								this.formData.store_head_image = uploadFileRes.data;
								console.log(uploadFileRes);
							}
						});
					},
					fail: (err) => {
						callback(file);
					},
				});

				uni.uploadFile({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/doUploadOfflineBusinessStoreHeadImage', //仅为示例，非真实的接口地址
					filePath: res.tempFilePaths[0],
					name: 'file',
					success: (uploadFileRes) => {
						this.formData.store_head_image = uploadFileRes.data;
						console.log(uploadFileRes);
					}
				});
			},
			bindChange(e) {
				let name = e.currentTarget.dataset.name;
				let value = e.detail.value
				this[name] = value;
			},
			openCL() {
				uni.chooseLocation({
					success: (res) => {
						if (res.provinceName) {
							this.formData.store_address_province = res.provinceName;
						}
						if (res.cityName) {
							this.formData.store_address_city = res.cityName;
						}
						this.formData.store_address = res.address;
						this.formData.store_tencent_latitude = res.latitude;
						this.formData.store_tencent_longitude = res.longitude;
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.uniui-location-filled ::v-deep {
		font-size: 25px !important;
	}

	.member-discount {
		line-height: 36px;
	}

	.eidt-button {
		width: 50%;
		margin: 30px auto;
	}

	.title {
		margin: 15px 0;
		color: #000;
		text-align: center;
	}

	.item-bg {
		background-color: #f2f3f8;
		padding: 10px 0;
		min-height: 80vh;
	}

	.canvas-position {
		position: absolute;
		top: -1000px;
	}

	.item_border {
		margin: 15px;
		padding: 15px 15px;
		border-radius: 15px;
		box-shadow: 0px 3px 5px 0px rgba(207, 207, 207, 0.39);
		background-color: white;
		color: #666;
	}

	.code-canvas {
		position: absolute;
		top: -1000px;
	}

	.my-forms {
		padding: 10px;
		margin: 10px 0;
	}

	.pick-time {
		display: flex;
		align-items: center;
		color: grey;

		.fenge {
			width: 20%;
			text-align: center;
		}

		.picker {
			border: 1px solid #e5e5e5;
			border-radius: 4px;
			font-size: 14px;
			padding: 8px 10px;
			width: 40%;

		}

	}

	.input-border {
		flex: 1 1 0;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		font-size: 14px;
		color: grey;
		padding: 8px 10px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.select-pic {
		min-height: 36px;
		line-height: 38px;
		padding: 0 10px;
		border: 1px solid #e5e5e5;
		width: 100px;
		text-align: center;
	}

	.ok-msg {
		height: 100px;
		line-height: 100px;
		text-align: center;
		margin-bottom: 20px;
		font-size: 20px;
	}

	.input-value {
		padding: 0 10px !important;
	}

	.agreement {
		font-size: 14px;
		color: #666666;
		display: flex;
		align-items: center;
		padding: 10px;

		.my-radio {
			transform: scale(0.7, 0.7)
		}

		text {
			text-decoration: underline;
		}
	}
</style>